package com.catersystem.zmy.catersystem.activity;

import android.content.Intent;
import android.os.Bundle;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.TextView;

import com.catersystem.zmy.catersystem.R;
import com.catersystem.zmy.catersystem.base.BaseActivity;
import com.catersystem.zmy.catersystem.bean.BehindBillsBean;
import com.catersystem.zmy.catersystem.bean.DishTypeBean;
import com.catersystem.zmy.catersystem.bean.DishesStatusBean;
import com.catersystem.zmy.catersystem.finals.FinalUrl;
import com.catersystem.zmy.catersystem.fragment.AllDishesFragment;
import com.catersystem.zmy.catersystem.fragment.DishesFragment;
import com.catersystem.zmy.catersystem.httputils.GetDataUtils;
import com.catersystem.zmy.catersystem.httputils.GsonUtil;
import com.catersystem.zmy.catersystem.httputils.HttpUtils;
import com.catersystem.zmy.catersystem.utils.DateUtil;
import com.catersystem.zmy.catersystem.utils.SPUtils;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Timer;
import java.util.TimerTask;

import butterknife.BindView;
import butterknife.OnClick;

public class HomeActivity extends BaseActivity {

    @BindView(R.id.tv_now_time)
    TextView tvNowTime;//系统时间
    @BindView(R.id.rb_all)
    RadioButton rbAll;//全部
    @BindView(R.id.rb_eat_in)
    RadioButton rbEatIn;//堂食
    @BindView(R.id.rb_eat_out)
    RadioButton rbEatOut;//外卖
    @BindView(R.id.rg_style)
    RadioGroup rgStyle;//食用方式
    @BindView(R.id.tv_no_cooking)
    public TextView tvNoCooking;//未烹饪
    @BindView(R.id.tv_cooking)
    public TextView tvCooking;//正在烹饪
    @BindView(R.id.tv_lately_complete)
    TextView tvLatelyComplete; //最近完成
    @BindView(R.id.tv_switch)
    TextView mTvSwitch; //菜单切换
    @BindView(R.id.tv_set)
    TextView tvSet;//设置


    private int id = 1;//切换显示  按单显示 or 按菜显示
    //第一次点击返回键的时间
    private long firstPressedTime;
    private Timer mTimer = new Timer();//定时器--更新系统时间
    private TimerTask mTimerTask;
    private Bundle mBundle;

    private DishesFragment mDishesFragment;//按菜显示
    private AllDishesFragment mAllDishesFragment;//按单显示
    private long mOpertime = DateUtil.getTodayTime();//按菜分类 默认时间为当天的8点 如果存在数据，读取最后一次的时间戳，去判断是否有新下的单
    private long mAllOpertime = DateUtil.getTodayTime();//按单分类 默认时间为当天的8点 如果存在数据，读取最后一次的时间戳，去判断是否有新下的单

    public int noCookingNum;//未烹饪的菜品数量
    public int cookingNum;//已烹饪的菜品数量


    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (mTimer != null) {//注销定时器
            mTimer.cancel();
            mTimer = null;
        }
    }

    public HomeActivity() {
        super(R.layout.activity_home);
    }

    protected void initView() {
        if (TextUtils.isEmpty(SPUtils.getInstance().getString("service_address"))) {//判断是否未设置服务器地址
            startActivityAndFinish(SettingActivity.class);
        }
        mDishesFragment = new DishesFragment();
        mAllDishesFragment = new AllDishesFragment();
        setSystemTime();//设置轮询及系统时间
        setOrderKind();
        rbAll.setChecked(true);
        rgStyle.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(RadioGroup group, int checkedId) {
                mDishesFragment.mDishTypeBeans.clear();
                switch (checkedId) {
                    case R.id.rb_all:
                        break;
                    case R.id.rb_eat_in:
                        break;
                    case R.id.rb_eat_out:
                        break;
                }
            }
        });
    }

    /**
     * 设置顶部时间显示更新
     */
    private void setSystemTime() {
        mTimerTask = new TimerTask() {
            @Override
            public void run() {
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        //设置时间
                        StringBuilder sb = new StringBuilder(DateUtil.toTime11(System.currentTimeMillis()));
                        sb.insert(11, "　" + DateUtil.getWeek(System.currentTimeMillis()) + "　");
                        tvNowTime.setText(sb);
                        if (id == 1) {//按菜显示 轮询查找是否有新订单
                            getDishesData(false);
                        } else {
                            getAllDishesData(false);
                        }
                        refreshDishesStatus();
                    }
                });
            }
        };
        mTimer.schedule(mTimerTask, 6000, 6000);
    }

    /**
     * 切换菜品显示界面
     */
    private void setOrderKind() {
        if (id == 1) {
            mTvSwitch.setClickable(false);
            noCookingNum = 0;
            cookingNum = 0;
            mTvSwitch.setText("按单分类");
            addFragment(R.id.fl_content, mDishesFragment);
            getDishesData(true);
        } else {
            mTvSwitch.setClickable(false);
            mTvSwitch.setText("按菜分类");
            addFragment(R.id.fl_content, mAllDishesFragment);
            getAllDishesData(true);
            tvSet.setFocusableInTouchMode(true);
            tvSet.requestFocus();
        }
    }

    /**
     * 按菜分类获取每道菜的菜品信息
     **/
    private void getDishesData(final boolean isFirst) {
        if (mDishesFragment.mDishTypeBeans.size() > 0) {
            mOpertime = mDishesFragment.mDishTypeBeans.get(0).getOpertime();
        }
        Map<String, String> data = new HashMap<>();
        data.put("orgcode", FinalUrl.getOrgCode());
        data.put("appguid", FinalUrl.getAppguid());
        data.put("tablename", "data_tabledetail");
        data.put("field", "id,item_name,masterno,spunit,amount,taste,status, UNIX_TIMESTAMP(opertime) as opertime");
        if (isFirst) {
            data.put("where", "status in(0,1) and `opertime` IS NOT NULL and UNIX_TIMESTAMP(`opertime`) > " +
                    DateUtil.getTodayTime() + " and `amount` > 0");
        } else {
            data.put("where", "status in(0,1)  and `opertime` IS NOT NULL and `amount` > 0 and UNIX_TIMESTAMP" +
                    "(`opertime`) > " + mOpertime + " and UNIX_TIMESTAMP(`opertime`) <" + System.currentTimeMillis());
        }
        GetDataUtils.getInstance().getDishData(data, this, isFirst, new HttpUtils.IHttpResult() {
            @Override
            public void onSuccess(String result) {
                mTvSwitch.setClickable(true);
                if (mDishesFragment.mBehindCookAdapter != null && GsonUtil.jsonToList(result, DishTypeBean.class)
                        .size() > 0) {
                    if (isFirst) {
                        mDishesFragment.mDishTypeBeans.clear();
                        mDishesFragment.mDishTypeBeans.addAll(GsonUtil.jsonToList(result, DishTypeBean.class));
                    } else {
                        mDishesFragment.mDishTypeBeans.addAll(0, GsonUtil.jsonToList(result, DishTypeBean.class));
                    }
                    mDishesFragment.setDishesWaitTime();
                    for (int i = 0; i < mDishesFragment.mDishTypeBeans.size(); i++) {
                        if (mDishesFragment.mDishTypeBeans.get(i).getStatus() == 0) {
                            noCookingNum++;
                        } else if (mDishesFragment.mDishTypeBeans.get(i).getStatus() == 1) {
                            cookingNum++;
                        }
                    }
                    mDishesFragment.mBehindCookAdapter.notifyDataSetChanged();
                    tvNoCooking.setText("未烹饪　" + noCookingNum + "");
                    tvCooking.setText("正在烹饪　" + cookingNum + "");
                }
            }
        });
    }


    /**
     * 按单分类获取整单的菜品信息
     **/
    private void getAllDishesData(final boolean isFirst) {
        if (mAllDishesFragment.billsBeenList.size() > 0) {
            mAllOpertime = mAllDishesFragment.billsBeenList.get(0).getOpentime();
        }
        Map<String, String> data = new HashMap<>();
        data.put("orgcode", FinalUrl.getOrgCode());
        if (isFirst) {
            data.put("timestamp", DateUtil.getTodayTime() + "");
            data.put("where", "status = '占用' ");
        } else {
            data.put("where", "status = '占用' and UNIX_TIMESTAMP(`opentime`) < " + System.currentTimeMillis() + " and " +
                    "UNIX_TIMESTAMP(`opentime`) > " + mAllOpertime);
        }
        GetDataUtils.getInstance().getAllDishData(data, this, isFirst, new HttpUtils.IHttpResult() {
            @Override
            public void onSuccess(String result) {
                mTvSwitch.setClickable(true);
                if (mAllDishesFragment.billsAdapter != null && GsonUtil.jsonToList(result, BehindBillsBean.class)
                        .size() > 0) {
                    if (isFirst) {//判断是否是切换或者第一次获取，否则为轮询
                        noCookingNum = 0;
                        mAllDishesFragment.billsBeenList.clear();
                        mAllDishesFragment.billsBeenList.addAll(GsonUtil.jsonToList(result, BehindBillsBean.class));
                    } else {
                        mAllDishesFragment.billsBeenList.addAll(0, GsonUtil.jsonToList(result, BehindBillsBean.class));
                    }
                    mAllDishesFragment.setDishesWaitTime();
                    for (int i = 0; i < mAllDishesFragment.billsBeenList.size(); i++) {
                        noCookingNum += mAllDishesFragment.billsBeenList.get(i).getDetail_uncompleted().size();
                    }
                    mAllDishesFragment.billsAdapter.notifyDataSetChanged();
                }
            }
        });
    }


    /**
     * 按单分类获取整单的菜品信息
     **/
    private void refreshDishesStatus() {
        Map<String, String> data = new HashMap<>();
        data.put("orgcode", FinalUrl.getOrgCode());
        GetDataUtils.getInstance().getDishesStatus(data, this, new HttpUtils.IHttpResult() {
            @Override
            public void onSuccess(String result) {
                List<DishesStatusBean> dishesStatusBeans = GsonUtil.jsonToList(result, DishesStatusBean.class);
                List<Integer> dishId = new ArrayList<>();
                dishId.clear();
                if (id == 1) {
                    for (int j = 0; j < mDishesFragment.mDishTypeBeans.size(); j++) {
                        for (int i = 0; i < dishesStatusBeans.size(); i++) {
                            if (mDishesFragment.mDishTypeBeans.get(j).getId() == dishesStatusBeans.get(i).getId()) {
                                mDishesFragment.mDishTypeBeans.get(j).setStatus(dishesStatusBeans.get(i).getStatus());
                                dishId.add(j);
                                mDishesFragment.mBehindCookAdapter.notifyDataSetChanged();
                            }
                        }
                        if (!dishId.contains(j)){
                            mDishesFragment.mDishTypeBeans.remove(j);
                            mDishesFragment.mBehindCookAdapter.notifyDataSetChanged();
                        }
                    }

                }
            }
        });
    }


    @OnClick({R.id.tv_switch, R.id.tv_lately_complete, R.id.tv_set})
    void onClick(View v) {
        switch (v.getId()) {
            case R.id.tv_switch://切换显示
                if (id == 1) {
                    id = 2;
                } else {
                    id = 1;
                }
                setOrderKind();
                break;
            case R.id.tv_lately_complete: //最近完成
                mBundle = new Bundle();
                mBundle.putInt("id", id);
                startActivityForResult(LatelyCompleteActivity.class, 1001, mBundle);
                break;
            case R.id.tv_set: //设置
                startActivity(SettingActivity.class);
                break;
        }
    }

    @Override
    public void onBackPressed() {
        //System.currentTimeMillis() 当前系统时间即第二次点击返回键的时间
        if (System.currentTimeMillis() - firstPressedTime < 2000) {
            super.onBackPressed();
        } else {
            showLongToast("再点一次退出");
            firstPressedTime = System.currentTimeMillis();
        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == RESULT_OK) {
            if (requestCode == 1001) {
                if (data != null) {
                    id = data.getIntExtra("id", 1);
                }
                setOrderKind();
            }
        }
    }

}
